<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { getLskCiaoRepos } from '@/api/gitee'
import Loading from '@/components/Loading.vue'
import { RESUME_GITEE_DATA } from '@/constant/localStore'
import { GITEE_URI } from '@/constant/Gitee'
import PcWorkCard from '@/layout/PC/components/PCWorkCard.vue'

import type { Params } from '@/types/Api'
import type { GiteeItem } from '@/types/Works'

const workData = ref<GiteeItem[]>([])
let isLoading = ref<boolean>(false)
let params = ref<Params>({
  page: 1,
  sort: 'created',
  per_page: 100
})

function formatTime(time: string): string {
  return new Date(time).toLocaleDateString()
}

function formatData(data: GiteeItem[]): GiteeItem[] {
  return data
    .filter((item) => item.description && item.description[0] === '#')
    .map((element) => {
      return {
        name: element.name,
        created_at: formatTime(element.created_at),
        updated_at: formatTime(element.updated_at),
        homepage: element.homepage,
        path: GITEE_URI + element.path,
        description: element.description.slice(1)
      }
    })
}

onMounted(() => {
  isLoading.value = true
  getLskCiaoRepos(params.value).then((res) => {
    // 该接口频繁调用可能会超出调用限制， 调用一次之后就存到本地， 如果遇到403 那么就从本次拿数据
    isLoading.value = false
    if (res.status === 403) {
      const data: string | null = localStorage.getItem(RESUME_GITEE_DATA)
      if (data) {
        workData.value = formatData(JSON.parse(data) as GiteeItem[])
        localStorage.setItem(RESUME_GITEE_DATA, JSON.stringify(res.data))
      } else {
        workData.value = []
      }
    } else {
      workData.value = formatData(res.data)
      localStorage.setItem(RESUME_GITEE_DATA, JSON.stringify(res.data))
    }
  })
})
</script>

<template>
  <Loading :loading="isLoading">
    <div class="work-container">
      <pc-work-card :work-data="workData" />
    </div>
  </Loading>
</template>
